/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.appspot.trick.it.admin.api;

import com.appspot.trick.it.admin.Util;
import com.appspot.trick.it.admin.db.SiteMstEntity;
import com.appspot.trick.it.admin.model.ArticleItemsModel;
import com.appspot.trick.it.admin.model.ArticleModel;
import com.google.api.client.auth.oauth2.Credential;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author takahara
 */
public class GaeArticleAPIService {
    private final SiteMstEntity siteMstEntity;
    private final GoogleOauthAPIService googleOauthAPIService;
    
    private static final String GET_BY_KEY_URI = "_ah/api/articleEndpoint/v1/getById?uniqueKey=";
    private static final String ADD_URI = "_ah/api/articleEndpoint/v1/add";
    private static final String UPDATE_URI = "_ah/api/articleEndpoint/v1/update";
    private static final String UPDATE_PUBLIC_FLG_URI = "_ah/api/articleEndpoint/v1/changePublicFlg";
    private static final String DELETE_URI = "_ah/api/articleEndpoint/v1/delete";
    private static final String GET_LIST_URI = "_ah/api/articleEndpoint/v1/getList";
    private static final String CHANGE_INDEX_URL = "_ah/api/articleEndpoint/v1/changeIndex";
    private static final String CHANGE_TITLE_URL = "_ah/api/articleEndpoint/v1/changeTitle";
    
    /**
     * コンストラクタ
     * @param siteMstEntity 
     * @throws java.io.IOException 
     */
    public GaeArticleAPIService(SiteMstEntity siteMstEntity) throws IOException {
        this.siteMstEntity = siteMstEntity;
        this.googleOauthAPIService = new GoogleOauthAPIService();
    }
    
    /**
     * 記事の追加
     * @param parentId
     * @param model
     * @return
     * @throws Exception 
     */
    public ArticleModel add(String parentId, ArticleModel model) throws Exception {

        // アクセストークンの更新
        Credential credential = googleOauthAPIService.getCredentials();

        Type responseModelType = new TypeToken<ArticleModel>() {
        }.getType();

        //POSTの内容を書き出す
        StringBuilder psb = new StringBuilder();
        psb.append("title=");
        psb.append(URLEncoder.encode(model.getTitle(), "utf-8"));
        psb.append("&");
        psb.append("parentId=");
        if (parentId != null) {
            psb.append(parentId);
        }
        

        return (ArticleModel) Http.postGetResponseJson(
                new URL(siteMstEntity.getDomin() + ADD_URI),
                psb.toString(),
                responseModelType,
                credential.getAccessToken());
    }
    
    /**
     * 記事の変更
     * @param model
     * @return
     * @throws Exception 
     */
    public ArticleModel changeTitle(ArticleModel model) throws Exception {

        // アクセストークンの更新
        Credential credential = googleOauthAPIService.getCredentials();

        Type responseModelType = new TypeToken<ArticleModel>() {
        }.getType();

        //POSTの内容を書き出す
        StringBuilder psb = new StringBuilder();
        psb.append("uniqueKey=");
        psb.append(model.getKey());
        psb.append("&");
        psb.append("title=");
        psb.append(URLEncoder.encode(model.getTitle(), "utf-8"));

        return (ArticleModel) Http.postGetResponseJson(
                new URL(siteMstEntity.getDomin() + CHANGE_TITLE_URL),
                psb.toString(),
                responseModelType,
                credential.getAccessToken());
    }
    
    /**
     * 記事の変更
     * @param model
     * @return
     * @throws Exception 
     */
    public ArticleModel update(ArticleModel model) throws Exception {

        // アクセストークンの更新
        Credential credential = googleOauthAPIService.getCredentials();

        Type responseModelType = new TypeToken<ArticleModel>() {
        }.getType();

        //POSTの内容を書き出す
        StringBuilder psb = new StringBuilder();
        psb.append("uniqueKey=");
        psb.append(model.getKey());
        psb.append("&");
        psb.append("title=");
        psb.append(URLEncoder.encode(model.getTitle(), "utf-8"));
        psb.append("&");
        psb.append("description=");
        if (model.getDescription() != null) {
            psb.append(URLEncoder.encode(model.getDescription(), "utf-8"));
        }
        psb.append("&");
        psb.append("keyWord=");
        if (model.getKeyWordList() != null && model.getKeyWordList().size() > 0 && Util.keywordListToString(model.getKeyWordList()) != null) {

            psb.append(URLEncoder.encode(Util.keywordListToString(model.getKeyWordList()), "utf-8"));
        }
        psb.append("&");
        psb.append("content=");
        if (model.getContent() != null) {
            psb.append(URLEncoder.encode(model.getContent(), "utf-8"));
        }
        psb.append("&");
        psb.append("googlePlusKey=");
        if (model.getGooglePlusKey() != null) {
            psb.append(model.getGooglePlusKey());
        }
        psb.append("&");
        psb.append("driveDriKey=");
        if (model.getDriveDriKey() != null) {
            psb.append(model.getDriveDriKey());
        }
        psb.append("&");
        psb.append("logoImageKey=");
        if (model.getLogoImageKey() != null) {
            psb.append(model.getLogoImageKey());
        }
        

        return (ArticleModel) Http.postGetResponseJson(
                new URL(siteMstEntity.getDomin() + UPDATE_URI),
                psb.toString(),
                responseModelType,
                credential.getAccessToken());
    }
    
    
    /**
     * 公開フラグの変更
     * @param key 
     * @throws java.lang.Exception 
     */
    public void changePublicFlg(String key) throws Exception {
        
        // アクセストークンの更新
        Credential credential = googleOauthAPIService.getCredentials();

        //POSTの内容を書き出す
        StringBuilder psb = new StringBuilder();
        psb.append("uniqueKey=");
        psb.append(key);

        Http.postOnle(
                new URL(siteMstEntity.getDomin() + UPDATE_PUBLIC_FLG_URI), 
                psb.toString(), 
                credential.getAccessToken());
    }
    
    /**
     * Indexの変更
     * @param categoryList
     * @throws Exception 
     */
    public void changeIndexs(List<ArticleModel> categoryList) throws Exception {
        
        // アクセストークンの更新
        Credential credential = googleOauthAPIService.getCredentials();

        //POSTの内容を書き出す
        StringBuilder psb = new StringBuilder();
        psb.append("articleIds=");
        
        List<String> keysList = new ArrayList();
        for(ArticleModel model: categoryList) {
            keysList.add(model.getKey());
        }
        
        psb.append(URLEncoder.encode(Util.keywordListToString(keysList), "utf-8"));
        
        Http.postOnle(
                new URL(siteMstEntity.getDomin() + CHANGE_INDEX_URL),
                psb.toString(), 
                credential.getAccessToken());
    }
    
    
    /**
     * 削除
     * @param key 
     * @throws java.lang.Exception 
     */
    public void delete(String key) throws Exception {
        
        // アクセストークンの更新
        Credential credential = googleOauthAPIService.getCredentials();
        
        //POSTの内容を書き出す
        StringBuilder psb = new StringBuilder();
        psb.append("uniqueKey=");
        psb.append(key);
        
        Http.postOnle(
                new URL(siteMstEntity.getDomin() + DELETE_URI), 
                psb.toString(), 
                credential.getAccessToken());

    }
    
    
    /**
     * 取得
     * @param key
     * @return 
     * @throws java.lang.Exception 
     */
    public ArticleModel getByKey(String key) throws Exception {
        
        // アクセストークンの更新
        Credential credential = googleOauthAPIService.getCredentials();
        
        String respons = Http.get(
                siteMstEntity.getDomin() + GET_BY_KEY_URI + key, credential.getAccessToken());
        Type responseModelType = new TypeToken<ArticleModel>() {}.getType();

        Gson gson = new Gson();
        
        ArticleModel model = gson.fromJson(respons, responseModelType);
        
        if(model.getKey() == null) {
            return null;
        }
        
        return model;
    }
    
    /**
     * 記事リストの取得
     * @param parentId
     * @return 
     * @throws java.lang.Exception 
     */
    public List<ArticleModel> getList(String parentId) throws Exception {
        
        // アクセストークンの更新
        Credential credential = googleOauthAPIService.getCredentials();
        
        String url = siteMstEntity.getDomin() + GET_LIST_URI;
        if(parentId != null) {
            url = url + "?parentId=" + parentId;
        }
        
        String response = Http.get(url, credential.getAccessToken());
        Type responseModelType = new TypeToken<ArticleItemsModel>() {}.getType();

        Gson gson = new Gson();
        ArticleItemsModel itemsModel = gson.fromJson(response, responseModelType);
        
        if(itemsModel.items == null) return new ArrayList();
        
        return itemsModel.items;

    }
    
}
